#include <fermat/net/tcp_client.h>
#include <fermat/net/socket_address.h>
#include <fermat/common/logging.h>
#include <fermat/net/socket_stream.h>
#include <functional>
#include <utility>
#include <vector>
#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <string>


int numThreads = 0;
size_t current = 0;

class Echoclient{
public:
    Echoclient(fermat::event::EventLoopPtr loop,  
				fermat::net::SocketAddress& listenAddr, 
				const std::string& id)
				: _loop(loop),
				  _client(loop, listenAddr, "EchoClient"+id)
	{
			_client.setConnectionCallback(std::bind(&Echoclient::onConnection, this, std::placeholders::_1));
			_client.setMessageCallback(std::bind(&Echoclient::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
            _client.setWriteCompleteCallback(std::bind(&Echoclient::onWriteComplete, this, std::placeholders::_1));
	}
		~Echoclient()
		{
		}
		void connect()
		{
			_client.connect();
		}
	private:
		void onConnection(const fermat::net::TcpConnectionPtr& conn)
		{
			if (conn->connected())    {
				++current;         
				LOG_INFO("*** connected ");    
			} else  {
                LOG_INFO("*** down ");    
            }
			 conn->send("world\n");

		}

		void onMessage(const fermat::net::TcpConnectionPtr& conn, fermat::PageBufferSliceQueuePtr buf, fermat::Timestamp time)
		{
			buf->clear();
			conn->send("hello");

		}

        void onWriteComplete(const fermat::net::TcpConnectionPtr& conn)
        {
            conn->send("world\n");
        }
		fermat::event::EventLoopPtr _loop;
		fermat::net::TcpClient      _client;

};


int main(int argc, char* argv[])
{  
	LOG_SET_LEVEL(fermat::log::ll_trace);
    LOG_INFO("pid = {} , tid = {}", getpid(), fermat::this_thread::tid());
	fermat::event::EventLoopPtr loop(new fermat::event::EventLoop());
	fermat::net::SocketAddress serverAddr;
	serverAddr.set("0.0.0.0", "2000");
    Echoclient client(loop, serverAddr, "1");
    client.connect();
    loop->loop();
}